var qcloud = require('../../vendor/wafer2-client-sdk/index');
var util = require('../../utils/util.js');
var config = require('../../config');
//index.js
//获取应用实例
const app = getApp()
Page({
    data: {
        open_id: '',
        order_id: '',
        hidden: true, //等待的展示与隐藏的控制
        buthidden: false, //按钮的可用和不可用的控制
        motto: 'Hello World',
        userInfo: {},
        hasUserInfo: false,
        payData: '',
        canIUse: wx.canIUse('button.open-type.getUserInfo')
    },
    // data: {
    //     motto: 'Hello World',
    //     userInfo: {},
    //     hasUserInfo: false,
    //     canIUse: wx.canIUse('button.open-type.getUserInfo')
    // },

    //获取二维码


    //事件处理函数
    bindViewTap: function() {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    
    //  onLoad: function (options) {
    //   options.id = 3;
    //   var that = this;
    //   wx.setNavigationBarTitle({
    //     title: '订单支付',
    //   });
    //   this.setData({
    //     order_id: options.id
    //   })
    //   // 获取本地数据-用户信息
    //   wx.getStorage({
    //     key: 'userInfo',
    //     // 能获取到则显示用户信息，保存信息到页面
    //     success: (json) => {
    //       //console.log(json);
    //       this.setData({
    //         userInfo: json.data.userInfo
    //       })
    //     }
    //   });
    //   //  https://boxapi.supergk.com/server/order/deal_money
    //   // 计算订单价格
    //   var _order_id = options.id;     
    //   var _uid = wx.getStorageSync("userInfo").userInfo.uid;
    //   console.log(_order_id);
    //   const requestSetOrderMoney = wx.request({
    //     url: "http://119.23.141.210:10335/server/order/deal_money",
    //     header: {
    //       "Content-Type": "application/x-www-form-urlencoded"
    //     },
    //     method: "POST",
    //     data: util.json2Form({ order_id: _order_id, user_id: _uid }),
    //     success: function (res) {
    //       console.log(res);
    //       if (res.data.code == 0) {
    //         console.log(res.data.msg);
    //         that.setData({
    //           payData: res.data.data
    //         })
    //       } else {
    //         console.log(res.data.msg)
    //       }
    //     }
    //   })
    // },
    //支付订单
    orderPay: function() {
        var that = this;
        //显示等待、禁用按钮，后台返回错误则将true和false对调一下就是隐藏等待、启用按钮
        that.setData({
            buthidden: true
        })
        var open_id = wx.getStorageSync("userInfo").userInfo.openId;
        wx.request({
          url: 'http://121.41.17.124:8052/wxpay',
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: util.json2Form({
              open_id: open_id,
              session_key: '0p0QoXONeb4olQygkBtW6w==',
              shop_id: '1',
              money: '0.01',
              detail: '[{ "goods_id": 1, "num": 5 }, { "goods_id": 2, "num": 5 }]'
            }),
            success: function(res) {
                if (res.data.code == "0") {

                    //显示等待、禁用按钮，后台返回错误则将true和false对调一下就是隐藏等待、启用按钮
                    that.setData({
                        hidden: false,
                        buthidden: true
                    })
                    // 发起支付
                    wx.requestPayment({
                        'timeStamp': res.data.data.data.timeStamp,
                        'nonceStr': res.data.data.data.nonceStr,
                        'package': res.data.data.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.data.data.paySign,
                        'success': function(res) {
                            that.setData({
                                hidden: false,
                                buthidden: true
                            })
                            console.log("支付成功：")
                            console.log(res)
                            wx.showToast({
                                title: "支付成功",
                                duration: 3000
                            })
                        },
                        'fail': function(res) {
                            that.setData({
                                hidden: true,
                                buthidden: false
                            })
                            console.log("支付失败：" + res)
                            console.log(res)
                            wx.showToast({
                                title: "支付失败",
                                duration: 3000
                            })
                        }
                    })
                } else {                  
                    //显示等待、禁用按钮，后台返回错误则将true和false对调一下就是隐藏等待、启用按钮
                    that.setData({
                        hidden: true,
                        buthidden: false
                    })
                    console.log(res)
                    
                    console.log(res.data.msg)
                    console.log(res.data.data.err_code_des)
                    wx.showToast({
                        title: res.data.data.err_code_des,
                        duration: 3000
                    })
                }
            }
        })
    },
    // 创建订单
    createOrder: function() {
        var that = this;
        var user_id = wx.getStorageSync("userInfo").userInfo.uid;
        console.log(user_id);
        const requestgetBoxState = wx.request({
            url: "http://119.23.141.210:10335/server/order/create",
            header: {
                "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            data: util.json2Form({
                user_id: user_id
            }),
            success: function(result) {
                console.log(result)
                if (result.data.code == 0) {
                    console.log("订单创建成功");
                    console.log(result)
                    that.setData({
                        isLockedHide: 1, //创建订单成功
                        _order_id: result.data.data.order_id,
                        _order_bn: result.data.data.order_bn,
                        isCreateOrder: 1,
                        doClose: 1,
                        isLocked: 1,
                    });
                    wx.setNavigationBarTitle({
                        title: '订单创建成功',
                    })
                    // 存储当前订单信息
                } else {
                    console.log(result.data.msg)
                    wx.showModal({
                        title: '提示',
                        content: result.data.msg,
                        showCancel: false
                    })
                }
            }
        })
    },
    changeCode() {
        var _this = this
        let telephone = '18861855848'
        if (telephone.length != 11 || isNaN(telephone)) {
            wx.showModal({
                title: '提示',
                content: "请输入有效的手机号码",
                showCancel: false
            })
            setTimeout(function() {
                wx.hideToast()
            }, 2000)
            return
        }
        this.setData({
            codeDis: true
        })
        //发送短信验证码
        wx.request({
            url: "http://localhost/sousou_api/server/user/send_msg",
            data: util.json2Form({
                tel: '18861855848'
            }),
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function(res) {
                let data = res.data
                if (data.code == "0") {
                    wx.showToast({
                        title: "发送成功",
                        icon: "success"
                    })
                    _this.setData({
                        phoneCode: 60
                    })
                    let time = setInterval(() => {
                        let phoneCode = _this.data.phoneCode
                        phoneCode--
                        _this.setData({
                            phoneCode: phoneCode
                        })
                        if (phoneCode == 0) {
                            clearInterval(time)
                            _this.setData({
                                phoneCode: "获取验证码",
                                flag: true,
                                codeDis: false
                            })
                        }
                    }, 1000)
                } else {
                    _this.setData({
                        codeDis: false
                    })
                    wx.showModal({
                        title: "提示",
                        content: data.msg,
                        showCancel: false
                    })
                    setTimeout(function() {
                        wx.hideToast()
                    }, 2000)
                }
            }
        })
    },
    getUserInfo: function(e) {
        if (this.data.logged) return
        console.log('正在登录')
        var that = this
        // 调用登录接口
        qcloud.login({
            success(result) {
                if (result) {
                    console.log('登录成功1');
                    that.setData({
                        userInfo: result,
                        hasUserInfo: true,
                        ogged: true
                    })
                    wx.setStorage({
                        key: 'userInfo',
                        data: {
                            userInfo: result,
                            bType: "warn",
                            actionText: "退出登录"
                        },
                        success: function(res) {
                            // console.log("存储成功2")
                        },
                    })
                } else {
                    // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
                    qcloud.request({
                        url: config.service.requestUrl,
                        login: true,
                        success(result) {
                            console.log(result.data.data);
          
                            console.log('登录成功2');
                            // that.globalData.userInfo = result.data.data;
                            that.setData({
                                userInfo: result.data.data,
                                hasUserInfo: true,
                                ogged: true
                            })
                            wx.setStorage({
                                key: 'userInfo',
                                data: {
                                    userInfo: result.data.data,
                                    bType: "warn",
                                    actionText: "退出登录"
                                },
                                success: function(res) {
                                    // console.log("存储成功2")
                                },
                            })
                        },
                        fail(error) {
                            console.log('request fail', error)
                        }
                    })
                }
            },
            fail(error) {
                console.log('登录失败', error)
            }
        })
    },
})